package com.smartcar

import android.content.Context
import android.graphics.Bitmap
import android.renderscript.*

class NV21Image(context: Context) {
    private val rs: RenderScript
    private val yuvToRgbIntrinsic: ScriptIntrinsicYuvToRGB
    private var yuvType: Type.Builder? = null
    private var rgbaType: Type.Builder? = null
    private var `in`: Allocation? = null
    private var out: Allocation? = null
    fun toBitmap(nv21: ByteArray, width: Int, height: Int): Bitmap {
        if (yuvType == null) {
            yuvType = Type.Builder(rs, Element.U8(rs))
                .setX(nv21.size)
            `in` = Allocation.createTyped(rs, yuvType?.create(), Allocation.USAGE_SCRIPT)
            rgbaType =
                Type.Builder(rs, Element.RGBA_8888(rs))
                    .setX(width).setY(height)
            out = Allocation.createTyped(rs, rgbaType?.create(), Allocation.USAGE_SCRIPT)
        }
        `in`!!.copyFrom(nv21)
        yuvToRgbIntrinsic.setInput(`in`)
        yuvToRgbIntrinsic.forEach(out)
        val bmpout = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        out!!.copyTo(bmpout)
        return bmpout
    }

    init {
        rs = RenderScript.create(context)
        yuvToRgbIntrinsic =
            ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs))
    }
}